package com.cy.pj.sys.controller;

import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.common.util.PageUtil;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/user/")
@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @PatchMapping("/password/{sourcePassword}/{newPassword}/{confirmPassword}")
    public JsonResult doUpdatePassword(@PathVariable String sourcePassword,@PathVariable String newPassword,@PathVariable String confirmPassword){
        sysUserService.updatePassword(sourcePassword, newPassword, confirmPassword);
        return new JsonResult("update ok");
    }

    @GetMapping("login/{username}/{password}")
    public JsonResult doLogin(@PathVariable String username,@PathVariable String password){
        //基于 subject 对象将 token 提交给 securityManager
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = //参考官网
                new UsernamePasswordToken(username, password);
        subject.login(token);//提交给 securityManager
        JsonResult jr=new JsonResult("登录ok");
        jr.setData(username);
        return jr;
    }

    @RequiresPermissions("sys:user:view")
    @GetMapping
    public JsonResult doFindUsers(SysUser entity){
        return new JsonResult(PageUtil.startPage().doSelectPageInfo(()->{
            sysUserService.findUsers(entity);
        }));
    }

    @PostMapping
    public JsonResult doSaveUser(@RequestBody SysUser entity){
        sysUserService.saveUser(entity);
        return new JsonResult("save ok");
    }

    @GetMapping("{id}")
    public JsonResult doFindById(@PathVariable Integer id){
        return new JsonResult(sysUserService.findById(id));
    }

    @PutMapping
    public JsonResult doUpdateUser(@RequestBody SysUser entity){
        sysUserService.updateUser(entity);
        return new JsonResult("update ok");
    }

    @RequiresPermissions("sys:user:update")
    @PatchMapping("{id}/{valid}")
    public JsonResult doValidById(@PathVariable Integer id,@PathVariable Integer valid){
        sysUserService.validById(id, valid);
        return new JsonResult("update ok");
    }

}
